package top.zxybird.common.query;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * QueryUtils.
 * 
 * Created by zxybird on 2017/11/16.
 */
public class QueryUtils {

  private static final Pattern keywordPattern = Pattern.compile("\\b((?:AND)|(?:OR)|(?:NOT))\\b");

  public QueryUtils() {
  }

  public static String escapeQuery(String s) {
    s = escapeQueryChars(s);
    s = escapeQueryKeyword(s);
    return s;
  }

  public static String escapeQueryKeyword(String s) {
    Matcher matcher = keywordPattern.matcher(s);
    StringBuilder sb = new StringBuilder(256);

    int pos;
    for (pos = 0; matcher.find(); pos = matcher.end()) {
      int start = matcher.start();
      sb.append(s.substring(pos, start));
      sb.append("\\").append(matcher.group(1));
    }

    sb.append(s.substring(pos));
    return sb.toString();
  }

  public static String escapeQueryChars(String s) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      if (c == 92 || c == 43 || c == 45 || c == 33 || c == 40 || c == 41 || c == 58 || c == 94 || c == 91 || c == 93
          || c == 34 || c == 123 || c == 125 || c == 126 || c == 42 || c == 63 || c == 124 || c == 38 || c == 59
          || c == 47 || Character.isWhitespace(c)) {
        sb.append('\\');
      }

      sb.append(c);
    }

    return sb.toString();
  }

}
